﻿using System;
using System.Collections.Generic;
using System.Linq;
using AzureDiagMon.Common.Interfaces;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureDiagMon.Common.Helpers.Azure
{
    public class GenericTableServiceContext<T> : IAzureTableRepository<T> where T : TableServiceEntity
    {
        public TableServiceContext Context { get; private set; }
        public String TableName { get; private set; }

        public GenericTableServiceContext(TableServiceContext context, string tableName)
        {
            Context = context;
            TableName = tableName;
        }

        public void Add(T entity)
        {
            Context.AddObject(TableName, entity);
        }

        public void AddOrUpdate(T entity)
        {
            var existingItem = GenericEntities.Where(f => f.RowKey == entity.RowKey).FirstOrDefault();
            if (existingItem != null)
            {
                Context.Detach(existingItem);
                Context.AttachTo(TableName, entity, "*");
                Context.UpdateObject(entity);
            }
            else
            {
                Context.AddObject(TableName, entity);
            }
        }

        public void Delete(T entity)
        {
            Context.DeleteObject(entity);
        }

        public void Update(T entity)
        {
            Context.UpdateObject(entity);
        }

        public void SubmitChanges()
        {
            Context.SaveChanges();
        }

        public IQueryable<T> GenericEntities
        {
            get { return Context.CreateQuery<T>(TableName); }
        }
    }
}
